﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Globalization;

namespace crm_library
{
	public static class EnumExtensions
	{
		public static bool TryParse<T>(this Enum theEnum, string strValue, out T result)
		{
			var strTypeFixed = strValue.Replace(' ', '_');
			if (Enum.IsDefined(typeof(T), strTypeFixed))
			{
				result = (T)Enum.Parse(typeof(T), strTypeFixed, true);
				return true;
			}
			foreach (var value in Enum.GetNames(typeof(T)).Where(value => value.Equals(strTypeFixed, StringComparison.OrdinalIgnoreCase)))
			{
				result = (T)Enum.Parse(typeof(T), value);
				return true;
			}
			result = default(T);
			return false;
		}

		public static void ForEach(this Enum enumType, Action<Enum> action)
		{
			foreach (var type in Enum.GetValues(enumType.GetType()))
			{
				action((Enum)type);
			}
		}

		public static List<T> ToEnumList<T>(this T enumType) where T : struct, IConvertible
		{
			List<T> list = new List<T>();
			foreach (var value in Enum.GetValues(enumType.GetType()))
			{
				Type t = enumType.GetType();
				list.Add((T)value);
			}
			return list;
		}

		public static List<ListItem> ToListItemList<T>(this T enumType, bool useDescriptionAttribute = false) where T : struct, IConvertible
		{
			var list = new List<ListItem>();
			var values = enumType.ToEnumList();

			if (useDescriptionAttribute)
			{
				throw new NotImplementedException();
			}
			else
			{
				list = values.Select(value => new ListItem(value.ToString(), (value.ToInt32(NumberFormatInfo.InvariantInfo)).ToString())).ToList();
			}

			return list;
		}
	}

	
}
